package com.spring.component.framework.dao.datasource.druid;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

/**
 * drudi数据源配置类
 * 
 * @author liushihua
 * @since 2018年05月11日
 */
@Configuration
public class DruidDataSourceConfig {
  @Value("${spring.datasource.druid.loginUsername:}")
  private String loginUsername;
  @Value("${spring.datasource.druid.loginPassword:}")
  private String loginPassword;
  @Value("${spring.datasource.druid.allow:}")
  private String allow;
  @Value("${spring.datasource.druid.deny:}")
  private String deny;
  @Value("${spring.datasource.druid.resetEnable:false}")
  private String resetEnable;

  /**
   * 注册一个druid数据源, 虽然spring boot注册默认数据源时会注册druid数据源，但druid连接池的配置信息加载不到
   * 
   * @return
   */
  @Bean
  @ConfigurationProperties(prefix = "spring.datasource")
  public DruidDataSource dataSource() {
    // ConfigurationProperties加载指定前缀的配置信息到DruidDataSource
    return new DruidDataSource();
  }

  /**
   * 注册一个servlet，处理访问druid监控页面的请求http://127.0.0.1:8081/abc/druid/index.html
   * 
   * @return
   */
  @Bean
  public ServletRegistrationBean druidStatViewServlet() {
    ServletRegistrationBean servletRegistrationBean =
        new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    // 添加初始化参数：initParams
    // 白名单，多个用逗号隔开
    servletRegistrationBean.addInitParameter("allow", this.allow);
    // IP黑名单 (存在共同时，deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view
    // thispage.多个用逗号隔开
    servletRegistrationBean.addInitParameter("deny", this.deny);
    // 登录查看信息的账号密码.
    servletRegistrationBean.addInitParameter("loginUsername", this.loginUsername);
    servletRegistrationBean.addInitParameter("loginPassword", this.loginPassword);
    // 是否能够重置数据.
    servletRegistrationBean.addInitParameter("resetEnable", this.resetEnable);// 禁用HTML页面上的“Reset
    return servletRegistrationBean;
  }

  /**
   * 注册一个filter，过滤一些资源
   * 
   * @return
   */
  @Bean
  public FilterRegistrationBean druidStatFilter() {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    filterRegistrationBean.setName("druidWebStatFilter");
    // 添加过滤规则.
    filterRegistrationBean.addUrlPatterns("/*");
    // 添加忽略的格式信息.
    filterRegistrationBean.addInitParameter("exclusions",
        "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
  }
}
